package cn.learn.controller.cargo;

import cn.learn.base.BaseController;
import cn.learn.domain.cargo.ContractProduct;
import cn.learn.domain.cargo.ContractProductExample;
import cn.learn.domain.cargo.Factory;
import cn.learn.domain.cargo.FactoryExample;
import cn.learn.service.cargo.ContractProductService;
import cn.learn.service.cargo.FactoryService;
import cn.learn.utils.FileUploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/cargo/contractProduct")
public class ContractProductController extends BaseController {

    @Reference
    private ContractProductService contractProductService;
    @Reference
    private FactoryService factoryService;
    @Autowired
    private FileUploadUtil fileUploadUtil;

    /**
     * 展示合同订单内容
     * @param contractId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "list", name = "展示合同下的货物")
    public String list(String contractId, @RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "10") int pageSize) {
        // 查询指定合同下的货物 到页面展示
        ContractProductExample productExample = new ContractProductExample();
        ContractProductExample.Criteria criteria = productExample.createCriteria();
        // 设置条件（合同的id）
        criteria.andContractIdEqualTo(contractId);

        // 查询
        PageInfo pb = contractProductService.findAll(productExample, pageNum, pageSize);
        request.setAttribute("pageList",pb);

        // 生产货物的生产商家
        FactoryExample factoryExample = new FactoryExample();
        FactoryExample.Criteria factoryExampleCriteria = factoryExample.createCriteria();
        factoryExampleCriteria.andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList",factoryList);
        // 带着合同id去页面
        request.setAttribute("contractId",contractId);
        return "/cargo/product/product-list";
    }

    /**
     * 添加一条货物
     * @param contractProduct
     * @return
     */
    @RequestMapping(value = "/addOne", name = "添加一条货物")
    public String addOne(ContractProduct contractProduct,  MultipartFile productPhoto) throws Exception {
        contractProduct.setCompanyId(companyId);
        contractProduct.setCompanyName(companyName);
        // 将提交的图片上传到七牛云中
        String imgsrc = fileUploadUtil.upload(productPhoto);
        // 保存, 设置下图片地址
        contractProduct.setProductImage("http://"+imgsrc);
        contractProductService.save(contractProduct);
        return "redirect:/cargo/contractProduct/list.do?contractId="+contractProduct.getContractId();
    }

    /**
     * 修改货物 与 跳转到修改页面
     * @param contractProduct
     * @return
     */
    @RequestMapping(value = "/toUpdate", name = "修改货物")
    public String toUpdate(ContractProduct contractProduct, MultipartFile productPhoto) throws Exception {
        if (request.getMethod().equals("POST")) {
            contractProduct.setCompanyId(companyId);
            contractProduct.setCompanyName(companyName);
            contractProductService.update(contractProduct);
            return "redirect:/cargo/contractProduct/list.do?contractId=" + contractProduct.getContractId();
        }
        // 获取货物
        ContractProduct product = contractProductService.findById(contractProduct.getId());
        request.setAttribute("data", product);
        // 生产货物的生产厂家
        FactoryExample factoryExample = new FactoryExample();
        FactoryExample.Criteria criteria = factoryExample.createCriteria();
        criteria.andCtypeEqualTo("货物");
        List<Factory> list = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList", list);
        return "/cargo/product/product-update";
    }

    /**
     * 删除货物
     * @param id
     * @param contractId
     * @return
     */
    @RequestMapping(value = "delete", name = "删除")
    public String delete(String id, String contractId) {
        contractProductService.delete(id);
        return "redirect:/cargo/contractProduct/list.do?contractId=" + contractId;
    }

    @RequestMapping(value = "/toImport",name = "到上传货物页面")
    public String toImport(String contractId){
        //将合同id带到页面进行货物保存
        request.setAttribute("contractId",contractId);
        return "cargo/product/product-import";
    }

    /**
     * excel上传
     * @param contractId
     * @return
     */
    @RequestMapping(value = "import", name = "excel上传")
    public String imports(String contractId, MultipartFile file) throws IOException {
            // 创建一个对象集合 用来封装货物对象数据
            List<ContractProduct> list = new ArrayList();
            // 1 创建工作薄读取货物上传的excel表(以流的方式获取)
            Workbook wb = new XSSFWorkbook(file.getInputStream());
            //2 选择工作页
            Sheet st = wb.getSheetAt(0);
            //3 读取excel表中的每一个数据封装给ContractProduct
            for(int i = 1; i < st.getLastRowNum() + 1; i++){   //1 2
                //获取每一行
                Row row = st.getRow(i);
                // 一行一个数组 用来保存当前行数的数据
                Object[] arr = new Object[row.getLastCellNum()];  //10  arr[0]--arr[9]
                // 获取遍历每一行的总单元格
                for(int j = 1; j < row.getLastCellNum(); j++){  // 1--9
                    Cell cell = row.getCell(j);
                    if(cell != null){
                        arr[j] = getCellVale(cell);  // arr[1]=升华  arr[2]=xx001 arr[3]=1  arr[4]=PCS arr[5]=10
                    }
                }
                // 创建对象
                ContractProduct contractProduct = new ContractProduct(arr,companyId,companyName);
                //设置合同id
                contractProduct.setContractId(contractId);
                // 放入集合中
                list.add(contractProduct);
            }
            //4 保存
            contractProductService.saveProductExcel(list);
        // 最新货物页面展示货物数据
        return "redirect: /cargo/contractProduct/list.do?contractId="+contractId;
    }

    //判断每个单元格的类型，根据不同的类型获取不同的单元格数据
    private Object getCellVale(Cell cell) {
        Object obj = null;
        //获取单元格的类型
        CellType cellType = cell.getCellType();
        switch (cellType){
            case STRING:{
                obj = cell.getStringCellValue();
                break;
            }
            case BOOLEAN:{
                obj = cell.getBooleanCellValue();
                break;
            }
            case NUMERIC:{
                //NUMERIC：日期/数值
                if(DateUtil.isCellDateFormatted(cell)){
                    //日期
                    obj = cell.getDateCellValue();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    obj = simpleDateFormat.format(obj);
                }else {
                    //数值
                    obj = cell.getNumericCellValue();
                }
                break;
            }
            default:{
                break;
            }
        }
        return obj;
    }

}
